package cn.chenmixuexi.protocol.serializer;

import java.io.*;

public class JDKSerializer extends Serializer {

    @Override
    public <T> T deserialize(Class<T> clazz, byte[] bytes) {
        try {
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            T message = (T) ois.readObject();
            return message;
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException("反序列化失败",e);
        }
    }

    @Override
    public <T> byte[] serialize(T obj) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            return byteArrayOutputStream.toByteArray();
        }catch (IOException e){
            throw new RuntimeException("序列化失败",e);
        }
    }

    @Override
    public int getId() {
        return Java;
    }
}
